package com.ruoyi.wechat.service.impl;

import cn.hutool.core.date.ChineseDate;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.wechat.domain.BusinessWechat;
import com.ruoyi.wechat.domain.Weather;
import com.ruoyi.wechat.mapper.BusinessWechatMapper;
import com.ruoyi.wechat.service.IBusinessWechatService;
import com.ruoyi.wechat.utils.RainbowUtil;
import com.ruoyi.wechat.utils.WeatherUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 微信推送Service业务层处理
 *
 * @author ruoyi
 * @date 2022-08-29
 */
@Service
@Slf4j
public class BusinessWechatServiceImpl extends ServiceImpl<BusinessWechatMapper, BusinessWechat> implements IBusinessWechatService {


    @Autowired
    private static WxMpTemplateMsgService wxService;

    /**
     * 查询微信推送列表
     *
     * @param businessWechat 微信推送
     * @return 微信推送
     */
    @Override
    public List<BusinessWechat> selectBusinessWechatList(BusinessWechat businessWechat) {
        return baseMapper.selectBusinessWechatList(businessWechat);
    }


    @Override
    public void push() {
        List<BusinessWechat> businessWechats = baseMapper.selectBusinessWechatList(new BusinessWechat());
        for (BusinessWechat businessWechat : businessWechats) {
            // 构建模板消息
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    .templateId(businessWechat.getWechatTemplateId())
                    .build();
            // 计算天数
            Date birthDay = businessWechat.getBirthDay();
            templateMessage.addData(new WxMpTemplateData("zodiacDays", DateUtil.getZodiac(DateUtil.month(birthDay), DateUtil.dayOfMonth(birthDay)) + "", "#FFA500"));
            templateMessage.addData(new WxMpTemplateData("birthdays", DateUtil.between(DateUtil.parseDate(DateUtil.thisYear() + "-" + (DateUtil.month(birthDay) + 1) + "-" + DateUtil.dayOfMonth(birthDay)), DateUtil.date(), DateUnit.DAY) + "", "#00BFFF"));
            templateMessage.addData(new WxMpTemplateData("birthYear", DateUtil.ageOfNow(birthDay) + "", "#FF1493"));

            // 获取天气数据
            AjaxResult weatherResult = WeatherUtil.getWeather(businessWechat);
            StringBuilder messageAll = new StringBuilder();
            if (!"0".equals(weatherResult.get("msg"))) {
                messageAll.append("<br/>");
                messageAll.append(weatherResult.get("data"));
                templateMessage.addData(new WxMpTemplateData("weather", "***", "#00FFFF"));
            } else {
                Weather weather = (Weather) weatherResult.get("data");
                ChineseDate chineseDate = new ChineseDate(DateUtil.date());
                templateMessage.addData(new WxMpTemplateData("date", weather.getDate() + "  " + weather.getWeek(), "#00BFFF"));
                templateMessage.addData(new WxMpTemplateData("lunar", "农历" + chineseDate.getChineseYear() + "年" + chineseDate.getChineseMonth() + chineseDate.getChineseDay(), "#00BFFF"));
                templateMessage.addData(new WxMpTemplateData("weather", weather.getText_now(), "#00FFFF"));
                templateMessage.addData(new WxMpTemplateData("low", weather.getLow() + "", "#173177"));
                templateMessage.addData(new WxMpTemplateData("temp", weather.getTemp() + "", "#EE212D"));
                templateMessage.addData(new WxMpTemplateData("wc_day", weather.getWc_day() + "", "#EE212D"));
                templateMessage.addData(new WxMpTemplateData("wd_day", weather.getWd_day() + "", "#EE212D"));
                templateMessage.addData(new WxMpTemplateData("high", weather.getHigh() + "", "#FF6347"));
                templateMessage.addData(new WxMpTemplateData("city", weather.getCityName() + "", "#173177"));
            }

            // 天行数据接口
            AjaxResult rainbowResult = RainbowUtil.getRainbow(businessWechat);
            if (!"200".equals(rainbowResult.get("msg"))) {
                messageAll.append("<br/>");
                messageAll.append(rainbowResult.get("data"));
            } else {
                templateMessage.addData(new WxMpTemplateData("rainbow", (String) rainbowResult.get("data"), "#FF69B4"));
            }
//            // 备注
//            String remark = "❤";
//            if (loveDays % 365 == 0) {
//                remark = "\n今天是恋爱" + (loveDays / 365) + "周年纪念日!";
//            }
//            if (birthdays == 0) {
//                remark = "\n今天是生日,生日快乐呀!";
//            }
//            if (loveDays % 365 == 0 && birthdays == 0) {
//                remark = "\n今天是生日,也是恋爱" + (loveDays / 365) + "周年纪念日!";
//            }
//            templateMessage.addData(new WxMpTemplateData("remark", remark, "#FF1493"));

            WxMpTemplateMsgService service = getService(businessWechat);
            String userId = businessWechat.getWechatOpenId();
            templateMessage.setToUser(userId);
            try {
                service.sendTemplateMsg(templateMessage);
                log.info("成功推送给用户!" + messageAll);
            } catch (WxErrorException e) {
                messageAll.append(e.getMessage());
                log.info("推送结果:" + messageAll);
            }
        }

    }

    private static WxMpTemplateMsgService getService(BusinessWechat businessWechat) {
        if (wxService != null) {
            return wxService;
        }
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId(businessWechat.getWechatAppId());
        wxStorage.setSecret(businessWechat.getWechatSecret());
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        wxService = wxMpService.getTemplateMsgService();
        return wxService;
    }

}
